package com.chenxin.interact.handler.rcsHandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WcsConstants;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.dto.RcsContinueDTO;
import com.chenxin.interact.domain.dto.RcsResultHkDTO;
import com.chenxin.wms.domain.AgvTaskEntity;
import com.chenxin.wms.mapper.AgvTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component("continueTaskRequest")
public class ContinueTaskRequest {
    @Autowired
    private AgvTaskMapper agvTaskMapper;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void call(UrlMap urlMap) {
        // 检索是否存在任务继续指令
        QueryWrapper<AgvTaskEntity> continueQW = new QueryWrapper<>();
        continueQW.lambda().eq(AgvTaskEntity::getAgvStatus, WcsConstants.HK_STATUS_CONTINUE)
                .last("order by update_date limit 1");
        AgvTaskEntity continueTask = agvTaskMapper.selectOne(continueQW);
        if (continueTask == null) {
            return;
        }
        // 将任务继续数据封装RcsContinueDTO
        RcsContinueDTO continueDTO = new RcsContinueDTO();
        continueDTO.setReqCode(String.valueOf(System.currentTimeMillis()));
        continueDTO.setTaskCode(continueTask.getTaskCode());
        continueDTO.setReqTime(dateFormat.format(new Date()));
        // 通过接口将封装的任务下发至RCS系统
        WebClient client = WebClient.builder()
                .baseUrl(urlMap.getUriAdr())
                .build();

        RcsResultHkDTO response = client.post()
                .uri(urlMap.getUrlAdr())
                .bodyValue(continueDTO)
                .retrieve()
                .bodyToMono(RcsResultHkDTO.class)
                .block();

        assert response != null;
        // 收到反馈后根据反馈码做处理
        if (WcsConstants.PROC_CODE_SUCCESS.equals(response.getCode())) {
            continueTask.setAgvStatus(WcsConstants.HK_STATUS_TAKE);
            continueTask.setData("任务继续成功下发");
        } else {
            continueTask.setAgvStatus(WcsConstants.HK_STATUS_ERROR);
            continueTask.setData("任务继续下发失败，RCS反馈：" + response.getMessage());
        }
        // 更新任务信息
        continueTask.setReqTime(dateFormat.format(new Date()));
        continueTask.setUpdateDate(new Date());
        agvTaskMapper.updateById(continueTask);
    }
}
